package com.example.roam.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.roam.R;
import com.example.roam.api.Api;
import com.example.roam.model.gson.UpdatePassword;
import com.example.roam.model.gson.Verify;
import com.example.roam.utils.Constans;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.Md5Util;
import com.example.roam.utils.StatusBarUtils;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.HttpURLConnection;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//忘记密码
public class ForgetPasswordActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btnSendYzm;
    private Button btnCertain;
    private EditText emailEdit;
    private EditText passwordEdit;
    private EditText passwordAgainEdit;
    private EditText editYzm;
    private ImageView img_back;
    private static final String TAG = "ForgetPasswordActivity";
    private Retrofit retrofitEmail;
    private String email;
    private String password;
    private String passwordAgain;
    private ProgressDialog progressdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpassword);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色
        init();
        initData();
        initEvent();
    }

    private void initData() {

    }

    private void init(){
        progressdialog = new ProgressDialog(this);
        retrofitEmail = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).addConverterFactory(GsonConverterFactory.create()).build();
        emailEdit = findViewById(R.id.edit1);
        passwordEdit = findViewById(R.id.edit2);
        passwordAgainEdit = findViewById(R.id.edit3);
        editYzm = findViewById(R.id.editYzm);
        btnSendYzm = findViewById(R.id.btn_send_yzm);
        btnCertain = findViewById(R.id.btn_certain);
        img_back = findViewById(R.id.img_back);
    }

    private void initEvent(){
        img_back.setOnClickListener(this);
        btnSendYzm.setOnClickListener(this);
        btnCertain.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_back:
                clickImgBack();
                break;
            case R.id.btn_send_yzm:
                clickBtnSendYzm();
                break;
            case R.id.btn_certain:
                clickBtnCertain();
                break;
        }
    }

    private void clickBtnCertain() {
        String yzm = editYzm.getText().toString().trim();
        if(!TextUtils.isEmpty(yzm)) {
            progressdialog.setTitle("加载中...");
            progressdialog.show(); // 展示progressDialog对话框
            String patternEmailUrl = "http://47.108.249.115:8080/ShuDao0.0.2-1.0-SNAPSHOT/email/verify";
            FormBody formBody = new FormBody.Builder().add("inNumber",yzm ).build();
            HttpUtil.getPostResponse(patternEmailUrl, formBody, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    Toast.makeText(ForgetPasswordActivity.this,"网络错误...",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String string = response.body().string();
                    Gson gson = new Gson();
                    Verify verify = gson.fromJson(string, Verify.class);
                    if(verify.isSuccess() ){
                        try {
                            password = Md5Util.encodeByMd5(ForgetPasswordActivity.this.password+Constans.SALT);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        retrofitEmail.create(Api.class).updatePassword(ForgetPasswordActivity.this.password,email,"").enqueue(new retrofit2.Callback<UpdatePassword>() {
                            @Override
                            public void onResponse(retrofit2.Call<UpdatePassword> call, retrofit2.Response<UpdatePassword> response) {
                                if( response.body().isSuccess() ) {
                                    Toast.makeText(ForgetPasswordActivity.this,"修改成功！",Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(ForgetPasswordActivity.this,LoginActivity.class);
                                    ForgetPasswordActivity.this.startActivity(intent);
                                }else {
                                    Toast.makeText(ForgetPasswordActivity.this,"修改失败！",Toast.LENGTH_SHORT).show();
                                }
                                progressdialog.dismiss();

                            }

                            @Override
                            public void onFailure(retrofit2.Call<UpdatePassword> call, Throwable t) {
                                Toast.makeText(ForgetPasswordActivity.this,"修改失败！",Toast.LENGTH_SHORT).show();
                                progressdialog.dismiss();
                            }
                        });

                    }else {
                        Toast.makeText(ForgetPasswordActivity.this,"验证码错误！",Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }else {
            Toast.makeText(this,"验证码不能为空",Toast.LENGTH_SHORT).show();
        }


    }

    private void clickImgBack(){
        this.finish();
    }

    private void clickBtnSendYzm(){
        /**
         * 1. 邮箱，密码，确认密码。不能为空
         * 2. 确认密码和密码需要相同
         * 3. 密码大于6位
         * */

        email = emailEdit.getText().toString().trim();
        password = passwordEdit.getText().toString().trim();
        passwordAgain = passwordAgainEdit.getText().toString().trim();

        if(TextUtils.isEmpty(email)){
            Toast.makeText(ForgetPasswordActivity.this,"邮箱不能为空",Toast.LENGTH_SHORT).show();
        }else {
            if(TextUtils.isEmpty(password) || TextUtils.isEmpty(passwordAgain) || password.length() < 6 ){
                Toast.makeText(ForgetPasswordActivity.this,"密码和确认密码不为空且大于6",Toast.LENGTH_SHORT).show();
            }else {
                if(!password.equals(passwordAgain)){
                    Toast.makeText(ForgetPasswordActivity.this,"确认密码输入有误",Toast.LENGTH_SHORT).show();
                }else {
                    
                    sendEmailPattern(); //发送验证码

                }
            }
        }
    }

    private void sendEmailPattern(){  // 发送验证码！
        Log.i(TAG, "sendEmailPattern: email："+email);
        String codeUrl = "http://47.108.249.115:8080/ShuDao0.0.2-1.0-SNAPSHOT/email/put?tomail="+email;
        HttpUtil.getGetResponse(codeUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(ForgetPasswordActivity.this, "验证码发送失败...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if( response.code() == HttpURLConnection.HTTP_OK) {
                    ForgetPasswordActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ForgetPasswordActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
        wait2SendEmail();
    }

    private void wait2SendEmail(){
        btnSendYzm.setClickable(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int costTime = 30;
                while (costTime > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    int finalCostTime = costTime;
                    costTime--;
                    ForgetPasswordActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btnSendYzm.setText(finalCostTime +"s");

                        }
                    });
                }

                ForgetPasswordActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnSendYzm.setClickable(true);
                        btnSendYzm.setText("发送验证码");
                    }
                });
            }
        }).start();
    }

}